﻿
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Red.Core
{
    /// <summary>
    ///     Bunch of methods to operate on bitmaps
    /// </summary>
    public static class BitmapHelpers
    {
        /// <summary>
        ///     Creates bitmap with bgra32 pixel format
        /// </summary>
        public static WriteableBitmap CreateBitmap( int w, int h )
        {
            return new WriteableBitmap( w, h, 96, 96, PixelFormats.Bgra32, null );
        }

        /// <summary>
        ///     Fills bitmap pixel-by-pixel using custom pixel color provider functor
        /// </summary>
        public static void FillBitmap( WriteableBitmap bmp, Func<int, int, Color> generator )
        {
            int w = (int)bmp.Width;
            int h = (int)bmp.Height;
            Int32[] pixels = new Int32[h * w];

            int offset = 0;
            for ( int y = 0; y < h; ++y )
            {
                for ( int x = 0; x < w; ++x )
                {
                    Color clr = generator( x, y );
                    Int32 colorData = clr.A << 24 | clr.R << 16 | clr.G << 8 | clr.B << 0;
                    pixels[offset + x] = colorData;
                }
                offset += w;
            }
            var rect = new Int32Rect( 0, 0, w, h );
            bmp.WritePixels( rect, pixels, w * 4, 0, 0 );
        }
    }
}
